package com.ruoyi.web.controller.shopping;

import java.security.Key;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.jiuyou.clientController.config.ConfigClientController;
import com.mchange.lang.IntegerUtils;
import com.mchange.lang.LongUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.order.domain.StoreProductOrderHandle;
import com.ruoyi.shopping.domain.MallCoupons;
import com.ruoyi.shopping.service.IMallCouponsService;
import com.ruoyi.store.domain.Store;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.service.ISysConfigService;
import io.lettuce.core.codec.RedisCodec;
import lombok.val;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisConnectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.shopping.domain.MallCdk;
import com.ruoyi.shopping.service.IMallCdkService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import sun.misc.PostVMInitHook;

import javax.management.Query;

/**
 * 批量生成CDKController
 *
 * @author ruoyi
 * @date 2022-07-18
 */
@RestController
@RequestMapping("/shopping/mallCdk")
public class MallCdkController extends BaseController
{
    @Autowired
    private IMallCdkService mallCdkService;
    @Autowired
    private IMallCouponsService mallCouponsService;


    //cdk管理通过优惠券名称查询

    /**
     * 查询优惠券列表
     */
    @GetMapping("/listMallCoupons")
    public TableDataInfo list(MallCoupons mallCoupons)
    {    mallCoupons.setDistinctionCdkCoupon("cdk");
        List<MallCoupons> list = mallCouponsService.selectMallCouponsList(mallCoupons);
        return getDataTable(list);
    }


    /**
     * 批量生成CDK
     * cdKey:兑换码前三位
     * cdKeyNumber ： 生成的数量
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallCdk:list')")
    @PostMapping("/createCdk")
    public AjaxResult createCdk( Long cdKeyNumber,String cdKey ,Long couponId,Long lastTotal,String limitedState )
    {
        /*
        * 1 页面在执行过程中显示正在加载中 and  生成中 完成
        * 2 批量插入
        * 3 方法在执行中不允许方法进入，然后稍后再试
        * */
        //生成兑换码的数量后优惠券剩余数量也要相对应减小
        if ("Y".equals(limitedState)){
            MallCoupons mallCoupons = new MallCoupons();
            mallCoupons.setId(couponId);
            mallCoupons.setLastTotal(lastTotal-cdKeyNumber);
            mallCouponsService.updateMallCoupons(mallCoupons);
        }

        //批量生成CDK
        MallCdk mallCdk1 = new MallCdk();
        mallCdk1.getParams().put("startThree",cdKey);
        List<MallCdk> list = mallCdkService.selectMallCdkList(mallCdk1);
        Map<String,String > mapCdk=list.stream().collect(Collectors.toMap(MallCdk::getCdked,MallCdk::getCdked));
        ArrayList<MallCdk> insertMallCdklists = new ArrayList<>();
        for (int j = 0; j < cdKeyNumber ; j++) {
            MallCdk mallCdk = new MallCdk();
            String cdked= getCdk(cdKey,mapCdk);
            mallCdk.setCdked(cdked);//兑换码
            mallCdk.setCouponId(couponId);//获取优惠券id
            mallCdk.setIfConversion(DicConstants.SYS_N.getCode());
            insertMallCdklists.add(mallCdk);
        }
        mallCdkService.insertMallCdks(insertMallCdklists);
        return AjaxResult.success();

    }


    /**
     * 根据前三位生成cdk
     * @param start
     * @param mapAll
     * @return
     */
    private char charr[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray();
    private String getCdk(String start,Map<String,String> mapAll){
        StringBuilder cdk = new StringBuilder();
        for(int i=0;i<8;i++) {
            Random random=new Random();
            cdk.append(charr[random.nextInt(charr.length)]);
        }
        String result=start+cdk;
        if(mapAll.containsKey(result)){
            return getCdk(start,mapAll);
        }
        mapAll.put(result,result);
        return result;
    }

    /**
     * 查询批量生成CDK列表
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallCdk:list')")
    @GetMapping("/list")
    public TableDataInfo list(MallCdk mallCdk)
    {
        startPage();
        //根据分类名称查询
           if(null!=mallCdk.getCouponId()){
            List<MallCdk> list = mallCdkService.selectMallCdkList(mallCdk);
            list.forEach(e->{
                MallCoupons mallCoupons = mallCouponsService.selectMallCouponsById(e.getCouponId());
                e.setCouponName(mallCoupons.getCouponName());
            });
            return getDataTable(list);
        }
//查询所有
        List<MallCdk> list = mallCdkService.selectMallCdkList(mallCdk);
        List CouponIds =list.stream().map(MallCdk::getCouponId).distinct().collect(Collectors.toList());
        if (CouponIds.size()>0){
            List<MallCoupons> couponsValue = mallCouponsService.selectMallCouponsByIds(CouponIds);
            HashMap<Long, String> map = new HashMap<>();
            couponsValue.forEach(e->{
                map.put(e.getId(),e.getCouponName());
            });
            System.out.println(map);
            list.forEach(e->{
                e.setCouponName(map.get(e.getCouponId()));
            });
        }

        return getDataTable(list);
    }

    /**
     * 导出批量生成CDK列表
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallCdk:export')")
    @Log(title = "批量生成CDK", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(MallCdk mallCdk)
    {
        MallCoupons mallCoupons = mallCouponsService.selectMallCouponsById(mallCdk.getCouponId());
        List<MallCdk> list = mallCdkService.selectMallCdkList(mallCdk);
        list.forEach(e->{
            e.setCouponName(mallCoupons.getCouponName());
        });
        ExcelUtil<MallCdk> util = new ExcelUtil<MallCdk>(MallCdk.class);
        return util.exportExcel(list, "批量生成CDK数据");
    }

    /**
     * 获取批量生成CDK详细信息
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallCdk:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(mallCdkService.selectMallCdkById(id));
    }

    /**
     * 新增批量生成CDK
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallCdk:add')")
    @Log(title = "批量生成CDK", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MallCdk mallCdk)
    {
        return toAjax(mallCdkService.insertMallCdk(mallCdk));
    }

    /**
     * 修改批量生成CDK
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallCdk:edit')")
    @Log(title = "批量生成CDK", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MallCdk mallCdk)
    {
        mallCdk.setUpdateType(DicConstants.BUSINESS_Manager.getCode());
        return toAjax(mallCdkService.updateMallCdk(mallCdk));
    }

    /**
     * 删除批量生成CDK
     */
    @PreAuthorize("@ss.hasPermi('shopping:mallCdk:remove')")
    @Log(title = "批量生成CDK", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(mallCdkService.logicDeleteMallCdk(ids,DicConstants.BUSINESS_Manager.getCode(),SecurityUtils.getUserId()));
    }
}
